package engine

import (
	"fmt"
	"io"

	"github.com/gin-gonic/gin"
)

func (sae *SimpleAgentEngine) uploadFile(ctx *gin.Context) {
	_, err := sae.cfg.AuthProvider.GetUserInfo(ctx.Request)
	if err != nil {
		ctx.String(403, err.Error())
		return
	}
	form, err := ctx.MultipartForm()
	if err != nil {
		ctx.String(500, err.Error())
		return
	}
	pathList := []string{}
	for _, files := range form.File {
		for _, file := range files {
			fileId, fileToken, err := sae.cfg.StorageHandle.FileDao.Save(ctx, file)
			if err != nil {
				continue
			}
			pathList = append(pathList, fmt.Sprintf("/api/v1/file/%s/%s", fileId, fileToken))
		}
	}
	ctx.JSON(200, pathList)
}

func (sae *SimpleAgentEngine) downloadFile(ctx *gin.Context) {
	fileId := ctx.Param("fileId")
	fileToken := ctx.Param("fileToken")
	reader, cmpFileToken, contentType, err := sae.cfg.StorageHandle.FileDao.Get(ctx, fileId)
	if err != nil {
		ctx.String(404, err.Error())
		return
	}
	defer reader.Close()
	if fileToken != cmpFileToken {
		ctx.String(403, "wrong file token")
		return
	}
	ctx.Header("Content-Type", contentType)
	io.Copy(ctx.Writer, reader) //skip error check
}
